﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

namespace Daco.Web.FlashUpload.Handler
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpPostedFile postedFile = context.Request.Files[0];
            string rootPath = context.Request.QueryString["Path"];
            string sid = context.Request.Form["sid"];
            string fileName = sid + postedFile.FileName.ToLower().Replace(' ', '_');
            string filePath = context.Server.MapPath(rootPath + fileName);
            try
            {
                //string fileName = sid + postedFile.FileName.Replace(' ', '_');
                if (System.IO.File.Exists(context.Server.MapPath(rootPath + fileName)))
                    if (string.IsNullOrEmpty(context.Request.QueryString["Overwrite"]) || Convert.ToBoolean(context.Request.QueryString["Overwrite"]))
                    {
                        postedFile.SaveAs(context.Server.MapPath(rootPath + fileName));
                        context.Response.StatusCode = 200;
                    }
                    else
                    {
                        context.Response.StatusCode = 500;
                        context.Response.Write("An error has occured");
                    }
                else
                {
                    postedFile.SaveAs(context.Server.MapPath(rootPath + fileName));
                    context.Response.StatusCode = 200;
                }
            }
            //#if !DEBUG
            //catch (Exception) { context.Response.StatusCode = 500; } 
            //#else 
            catch (Exception ex) { context.Response.StatusCode = 500; string msg = ex.Message; }
            //#endif
            finally { context.Response.End(); }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
